package cn.ac.registAService.commons.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * @author yangzhong E-mail: zyang@ceode.ac.cn
 * @version 1.0
 * @date 2012-10-16 下午4:40:00
 * @fuction 对系统xml解析提供支持
 */

public class XmlReader {

	// 目前不用了
	//保存中间值(方法getElementByName用)
	// private static ArrayList<Element> alParent=new ArrayList<Element>();

	/**
	 * 读取XML文件,获得document对象
	 * 
	 * @param filePath
	 *            xml文件路径
	 * @return document对象
	 * @throws DocumentException 
	 */
	public static Document getDocument(String filePath) throws DocumentException 
	{
		Document document = null;
		SAXReader reader = new SAXReader();

		// 加入命名空间
		Map map = new HashMap();
		map.put("csw", "http://www.opengis.net/cat/csw/2.0.2");
		map.put("gmd", "http://www.isotc211.org/2005/gmd");
		map.put("gco", "http://www.isotc211.org/2005/gco");
		map.put("gml", "http://www.opengis.net/gml");
		map.put("ogc","http://www.opengis.net/ogc");
		map.put("geonet", "http://www.fao.org/geonetwork");

		reader.getDocumentFactory().setXPathNamespaceURIs(map);

		File file = new File(filePath);

			document = reader.read(file);

		return document;
	}
	
     /**
      * 将字符串转换为xml
      * @param strXml
      * @return
      * @throws DocumentException
      */
	 public static Document StringToXml(String strXml) throws DocumentException
	 {
		 Document document=DocumentHelper.parseText(strXml);
        return document;
	 }

     /** 
      * 格式化XML文档 
      * 
      * @param document xml文档 
      * @param istrans    是否对属性和元素值进行转移 ,true转义，false不转义
      * @return 格式化后XML字符串 
      */ 
     public static String formatXml(Document document, boolean istrans) { 
             OutputFormat format = OutputFormat.createPrettyPrint();
             //format.setEncoding(charset);  //字符串的编码
             StringWriter sw = new StringWriter(); 
             XMLWriter xw = new XMLWriter(sw, format); 
             xw.setEscapeText(istrans); 
             try { 
                     xw.write(document); 
                     xw.flush(); 
                     xw.close(); 
             } catch (IOException e) { 
                     System.out.println("格式化XML文档发生异常，请检查！"); 
                     e.printStackTrace(); 
             } 
             return sw.toString(); 
     }  //end formatXml
}
	 


